package dao;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import model.Behandling;
import model.Lager;
import model.MellemVare;
import model.ProduktType;

/**
 * 
 * @author Martin Sax
 * 
 */
public class Dao {

	private static Dao unikInstance;

	private EntityManagerFactory emf = Persistence
			.createEntityManagerFactory("dmu");
	private EntityManager em = emf.createEntityManager();
	private EntityTransaction tx = em.getTransaction();

	private Dao() {
		// Singleton
	}

	public static Dao getUnikInstance() {
		if (unikInstance == null) {
			unikInstance = new Dao();
		}
		return unikInstance;
	}

	public List<ProduktType> getProduktTyper() {
		ArrayList<ProduktType> ptl = new ArrayList<ProduktType>(em.createQuery(
				"SELECT p FROM ProduktType p", ProduktType.class)
				.getResultList());
		int i = 0;
		while (i < ptl.size()) {
			if (ptl.get(i) instanceof MellemVare) {
				ptl.remove(i);
			} else {
				i++;
			}
		}

		return ptl;
	}

	public void storeProduktType(ProduktType produktType) {
		tx.begin();
		em.persist(produktType);
		tx.commit();
	}

	public void removeProduktType(ProduktType produktType) {
		tx.begin();
		em.remove(produktType);
		tx.commit();
	}

	public List<Behandling> getBehandlinger() {
		return em.createQuery("SELECT b FROM Behandling b", Behandling.class)
				.getResultList();
	}

	public void storeBehandlinger(Behandling behandling) {
		tx.begin();
		em.persist(behandling);
		tx.commit();
	}

	public void removeBehandlinger(Behandling behandling) {
		tx.begin();
		em.remove(behandling);
		tx.commit();
	}

	public List<MellemVare> getMellemvarer() {
		return em.createQuery(
				"SELECT m FROM MellemVare m ORDER BY m.vareNummer",
				MellemVare.class).getResultList();
	}

	public void storeMellemvare(MellemVare mellemvare) {
		tx.begin();
		em.persist(mellemvare);
		tx.commit();
	}

	public void removeMellemvare(MellemVare mellemvare) {
		tx.begin();
		em.remove(mellemvare);
		tx.commit();
	}

	public Lager getLager() {
		return em.createQuery("SELECT l FROM Lager l", Lager.class)
				.getSingleResult();
	}

	public void createLager() {
		tx.begin();
		em.persist(Lager.getInstance());
		tx.commit();

	}
}